package com.ming.attendance.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import com.ming.attendance.po.WxUser;

import java.util.Calendar;

public class JWTUtils {

    private static String secretKey = "onv2345nlk2jnlk4j52ib34b5ibl2";

    // 获取token
    public static String getToken(WxUser user){
        // 设置过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,3);
        // 设置保密内容
        JWTCreator.Builder builder = JWT.create();
        return builder.withExpiresAt(instance.getTime())
                .withClaim("openid",user.getOpenid())
                .withClaim("session_key",user.getSessionKey())
                .sign(Algorithm.HMAC256(secretKey));
    }
    // 验证token的openid
    public static DecodedJWT verify(String token) {
        Verification require = JWT.require(Algorithm.HMAC256(secretKey));
        DecodedJWT verify = require.build().verify(token);
        return verify;
    }

    // 获取token中的openid
    public static String getOpenid(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT.getClaim("openid").asString();
    }

    // 获取token中的session_key
    public static String getSessionKey(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secretKey)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT.getClaim("session_key").asString();
    }
}
